package io.gitee.dtdage.app.boot.starter.pay.zfb.utils;

import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import io.gitee.dtdage.app.boot.starter.common.utils.function.Function;
import io.gitee.dtdage.app.boot.starter.pay.zfb.context.ConfigBean;

/**
 * 支付宝SDK工具类
 *
 * @author WFT
 * @since 2024/4/14
 */
public class ZfbSDKUtil {

    /**
     * 私有化构造函数
     */
    private ZfbSDKUtil() {

    }

    /**
     * 以静态内部类实例化当前对象,从而达到懒汉式单例的效果
     */
    private static class Holder {

        private final static ZfbSDKUtil INSTANCE = new ZfbSDKUtil();

    }

    /**
     * 获取当前实例对象
     *
     * @return {@link ZfbSDKUtil}
     */
    public static ZfbSDKUtil getInstance() {
        return Holder.INSTANCE;
    }

    public double priceFormat(Integer price) {
        return ((double) price) / 100;
    }

    public <R extends AlipayResponse> String execute(Function<AlipayClient, R> callback, ConfigBean configure) throws Exception {
        //  创建客户端对象
        com.alipay.api.AlipayConfig config = new com.alipay.api.AlipayConfig();
        //  API 网关
        config.setServerUrl("https://openapi.alipay.com/gateway.do");
        //  应用编号,应用私钥,支付宝公钥
        config.setAppId(configure.getAppId());
        config.setPrivateKey(configure.getPrivateKey());
        config.setAlipayPublicKey(configure.getPublicKey());
        //  格式,编码,加密方式
        config.setFormat("json");
        config.setCharset("utf-8");
        config.setSignType("RSA2");
        //  证书
        config.setAppCertPath(configure.getAppCertPath());
        config.setAlipayPublicCertPath(configure.getZfbCertPath());
        config.setRootCertPath(configure.getRootCertPath());
        //  调用接口
        R response = callback.apply(new DefaultAlipayClient(config));
        if (response.isSuccess()) {
            return response.getBody();
        }
        throw new RuntimeException(response.getSubMsg());
    }

}
